﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections;
using System.Linq;

namespace JNPF.Utils.Controller
{
    /// <summary>
    /// 模型验证
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.21 
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class ValidModelAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 模型验证
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var errorht = new Hashtable();
                var errors = context.ModelState.Where(m => m.Value.Errors.Any()).Select(x => new { x.Key, x.Value.Errors });
                foreach (var item in errors)
                {
                    var fieldErrors = item.Errors.Select(i => i.ErrorMessage).First<string>();
                    errorht[item.Key] = fieldErrors;
                }
                context.Result = new JsonResult(new ResponseResult() { code = ResponseCode.ValidateError, msg = errorht.ToJson() });
            }
        }
    }
}
